<template>
    <div>
        <a href="#" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#uploadimage">修改头像</a>
        <div class="modal-styles modal fade" id="uploadimage" tabindex="-1" aria-labelledby="uploadimage"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">修改头像</h5>
                        <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"><i
                                class="fa-regular fa-circle-xmark"></i></button>
                    </div>
                    <div class="modal-body">
                        <div class="addpaymethod-form add-course-info">
                            <img id="imagePreview" :src="modelValue">
                        </div>
                        <input type="file" id="file" class="form-control" @change="uploadImg" />
                        <a class="btn btn-success">点击选择</a>
                    </div>
                    <div class="modal-footer me-auto">
                        <button type="button" class="btn btn-modal-style btn-theme" @click="save">保存</button>
                        <button type="button" class="btn btn-modal-style btn-cancel" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
const userInfo = useUseInfo()
// import fileApi from '@/composables/fileApi.js'
const uploadImg = e => {
    console.log(e.target.files[0])
    const file = e.target.files[0]
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            imagePreview.src = e.target.result;
            imagePreview.style.display = 'inline';
        };
        reader.readAsDataURL(file);
    }
}
/**
 * 上传头像
 * 1. 调用接口，传入图片
 * 2. 调用接口，更新老师头像
 * 3. 关闭弹层
 */
const save = async () => {
    const file = document.getElementById('file').files[0]
    const data = new FormData()
    data.append('file', file)
    const res = await fileApi.uploadImg(data)
    if (userInfo.value.user.type == 'teacher')
        await teacherApi.put(userInfo.value.user.id, { avatar: res.uploadedFile.url })
    else if (userInfo.value.user.type == 'master')
        await masterApi.put(userInfo.value.user.id, { avatar: res.uploadedFile.url })

    emit('update:modelValue', res.uploadedFile.url)
    userInfo.value.user.avatar = res.uploadedFile.url
    toast('修改头像OK')
    $('#uploadimage').modal('hide')
    // 关闭弹层

}
// v-model

defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['update:modelValue'])


</script>
